package tech.powerjob.official.processors.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import tech.powerjob.common.exception.PowerJobException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * JSON工具类
 *
 * @author tjq
 * @since 2020/4/16
 */
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    }

    public static String toJSONString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        }catch (Exception ignore) {
        }
        return null;
    }

    public static String toJSONStringUnsafe(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        }catch (Exception e) {
            throw new PowerJobException(e);
        }
    }

    public static byte[] toBytes(Object obj) {
        try {
            return objectMapper.writeValueAsBytes(obj);
        }catch (Exception ignore) {
        }
        return null;
    }

    public static <T> T parseObject(String json, Class<T> clz) throws JsonProcessingException {
        return objectMapper.readValue(json, clz);
    }

    public static <T> T parseObject(byte[] b, Class<T> clz) throws Exception {
        return objectMapper.readValue(b, clz);
    }

    public static <T> T parseObject(byte[] b, TypeReference<T> typeReference) throws Exception {
        return objectMapper.readValue(b, typeReference);
    }

    public static <T> T parseObjectUnsafe(String json, Class<T> clz) {
        try {
            return objectMapper.readValue(json, clz);
        }catch (Exception e) {
            ExceptionUtils.rethrow(e);
        }
        throw new PowerJobException("impossible");
    }

    /**
     * <B>方法名称：</B>校验是否是有效JSON数据<BR>
     * <B>概要说明：</B>由于JAVA正则表达式没法递归，不能一个表达式进行匹配，只能用JAVA进行递归
     * 字符串传来后进行匹配，普通类型数据仅匹配格式不捕获，将可能的JSON类型（[] {}）进行捕获，
     * 递归进行校验，共设置四个捕获组，为了保证逗号分隔的格式是严格正确的，没有想到好的方法简化正则表达式
     * 只能把数据分成两类，一类带逗号一类不带分别进行匹配.由于捕获组仅能匹配最后一个捕获结果，所以需要手动 进行字符串截取进行递归验证。
     *
     * 严格按照JSON官网给出的数据格式 双引号引起来的字符串 数字 JSONOBJECT JSONARRAY 波尔值和JSONNull
     * 在[]{}以及逗号前后可以有任意空字符。 <BR>
     *
     * @param value 数据
     * @return boolean 是/不是
     */
    public static Boolean isJsonStr(String value) {
        if (StringUtils.isBlank(value) || ((!value.startsWith("[") && !value.endsWith("]")) && (!value.startsWith("{") && !value.endsWith("}")))) {
            return false;
        }
        try {
            boolean result = false;
            String jsonRegexp = "^(?:(?:\\s*\\[\\s*(?:(?:"
                    + "(?:\"[^\"]*?\")|(?:true|false|null)|(?:[+-]?\\d+(?:\\.?\\d+)?(?:[eE][+-]?\\d+)?)|(?<json1>(?:\\[.*?\\])|(?:\\{.*?\\})))\\s*,\\s*)*(?:"
                    + "(?:\"[^\"]*?\")|(?:true|false|null)|(?:[+-]?\\d+(?:\\.?\\d+)?(?:[eE][+-]?\\d+)?)|(?<json2>(?:\\[.*?\\])|(?:\\{.*?\\})))\\s*\\]\\s*)"
                    + "|(?:\\s*\\{\\s*"
                    + "(?:\"[^\"]*?\"\\s*:\\s*(?:(?:\"[^\"]*?\")|(?:true|false|null)|(?:[+-]?\\d+(?:\\.?\\d+)?(?:[eE][+-]?\\d+)?)|(?<json3>(?:\\[.*?\\])|(?:\\{.*?\\})))\\s*,\\s*)*"
                    + "(?:\"[^\"]*?\"\\s*:\\s*(?:(?:\"[^\"]*?\")|(?:true|false|null)|(?:[+-]?\\d+(?:\\.?\\d+)?(?:[eE][+-]?\\d+)?)|(?<json4>(?:\\[.*?\\])|(?:\\{.*?\\}))))\\s*\\}\\s*))$";

            Pattern jsonPattern = Pattern.compile(jsonRegexp);

            Matcher jsonMatcher = jsonPattern.matcher(value);

            if (jsonMatcher.matches()) {
                result = true;
                for (int i = 4; i >= 1; i--) {
                    if (!StringUtils.isEmpty(jsonMatcher.group("json" + i))) {
                        result = JsonUtils.isJsonStr(jsonMatcher.group("json" + i));
                        if (!result) {
                            break;
                        }
                        if (i == 3 || i == 1) {
                            result = JsonUtils.isJsonStr(value.substring(0, jsonMatcher.start("json" + i))
                                    + (i == 3 ? "\"JSON\"}" : "\"JSON\"]"));
                            if (!result) {
                                break;
                            }
                        }
                    }
                }

            }
            return result;
        } catch (Exception e) {
            return false;
        }
    }

    // public static void main(String[] args) {
    //     System.out.println(isJsonStr("[\"value1\", \"value2\", \"value3\"]"));
    //     System.out.println(isJsonStr("{\"value1\", \"value2\", \"value3\"}"));
    //     System.out.println(isJsonStr("[\"value1\", \"value2\", \"value3\"}"));
    //     System.out.println(isJsonStr("{\"value1\", \"value2\", \"value3\"]"));
    //
    //     System.out.println(isJsonStr("[\"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\"]"));
    //     System.out.println(isJsonStr("{\"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\"}"));
    //     System.out.println(isJsonStr("{\"key1\",\"value1\", \"key2\",\"value2\", \"key3\",\"value3\"}"));
    //     System.out.println(isJsonStr("[\"key1\",\"value1\", \"key2\",\"value2\", \"key3\",\"value3\"}"));
    //     System.out.println(isJsonStr("{\"key1\",\"value1\", \"key2\",\"value2\", \"key3\",\"value3\"]"));
    // }
}
